﻿using UnityEngine;
using UnityEngine.UI;

public class SpriteChanger : MonoBehaviour
{
    public enum GraphicType
    {
        Image,
        SpriteRender,
    }

    public GraphicType graphicType = GraphicType.Image;
    public Sprite[] sprites;
    Image image;
    public bool autoNativeSize = false;

    public bool isLoop = false;
    public float interval = 0.5f;
    private float lastTime = 0;
    private int lastIndex = 0;
    public Sprite[] loopSprites;

    void Awake()
    {
    }

    void Update()
    {
        if (!isLoop)
            return;
        if (Time.realtimeSinceStartup - lastTime < interval)
            return;
        lastIndex = lastIndex + 1 >= loopSprites.Length ? 0 : lastIndex + 1;
        ChangeToLoopIndex(lastIndex);
        lastTime = Time.realtimeSinceStartup;
    }

    public void SetLoopInterval(float interval)
    {
        this.interval = interval;
    }

    public void EnableLoop(bool isLoop)
    {
        this.isLoop = isLoop;
    }

    public void ChangeToLoopIndex(int idx)
    {
        if (idx < 0 || idx >= loopSprites.Length || loopSprites[idx] == null)
            return;
        if (graphicType == GraphicType.Image)
            ChangeSprite_Image(loopSprites[idx]);
        else
            ChangeSprite_SpriteRenderer(loopSprites[idx]);
    }

    public void ChangeToIndex(int idx)
    {
        if (idx < 0 || idx >= sprites.Length || sprites[idx] == null)
            return;
        if (graphicType == GraphicType.Image)
            ChangeSprite_Image(sprites[idx]);
        else
            ChangeSprite_SpriteRenderer(sprites[idx]);
    }

    public void ChangeSprite_SpriteRenderer(Sprite sprite)
    {
        SpriteRenderer sr = GetComponent<SpriteRenderer>();
        if (sprite != null)
            sr.sprite = sprite;
    }

    public void ChangeSprite_Image(Sprite sprite)
    {
        if (image == null)
            image = GetComponent<Image>();
        if (image)
        {
            image.sprite = sprite;
            if (autoNativeSize)
            {
                image.SetNativeSize();
            }
        }
    }

    public void ReplaceSprite(int index, Sprite sprite)
    {
        if (index < 0 || index >= sprites.Length)
            return;
        sprites[index] = sprite;
    }

    public void ExchangeSprite(int fdx, int tdx)
    {
        if (fdx < 0 || tdx < 0 || fdx >= sprites.Length || tdx >= sprites.Length)
            return;
        if (sprites[fdx] && sprites[tdx])
        {
            Sprite spr = sprites[tdx];
            sprites[tdx] = sprites[fdx];
            sprites[fdx] = spr;
        }
    }
}